
#include "mystring.h"
#include <string.h>

using namespace std;

//构造函数
mystring::mystring(const char * str)
{
    if(str == NULL)
    {
        _str  = new char[1];
        *_str = '\0';
    }
    else
    {
        int len = strlen(str);
        _str = new char[len + 1];
        strcpy(_str, str);
    }
}

//析构函数
mystring::~mystring()
{
    delete []_str;
}

//拷贝构造（深拷贝）
mystring::mystring(const mystring & other)
{
    int len = strlen(other._str);
    this->_str = new char[len+1];
    strcpy(this->_str, other._str);
}

//赋值运算符重载
mystring &mystring::operator=(const mystring &another)
{
    if(this == &another)
    {
        return *this;
    }
    else
    {
        delete []this->_str;
        int len = strlen(another._str);
        this->_str = new char[len+1];
        strcpy(this->_str, another._str);
        return *this;
    }
}

//加法运算符重载
mystring mystring::operator+(const mystring &other)
{
    int len = strlen(this->_str) + strlen(other._str);
    
    mystring str;
    delete []str._str;

    str._str = new char[len + 1];
    memset(str._str, 0 , len+1);

    strcat(str._str, this->_str);
    strcat(str._str, other._str);

    return str;
}

//关系运算符重载
bool mystring::operator==(const mystring &other)
{
    if(strcmp(this->_str, other._str) == 0)
        return true;
    else
        return false;
}

bool mystring::operator>(const mystring &other)
{
    if(strcmp(this->_str, other._str) > 0)
        return true;
    else
        return false;
}

bool mystring::operator<(const mystring &other)
{
    if(strcmp(this->_str, other._str) < 0)
        return true;
    else
        return false;
}

//[]运算符重载
char &mystring::operator[](int idx)
{
    return _str[idx];
}

//display
void mystring::dis()
{
    cout<<"The str = "<<_str<<endl;
}

int main(void)
{
    //mystring st("china");
    mystring st = "holle";
    st.dis();
    mystring st2 = st;
    st2.dis();

    mystring st3 = st2 = st;
    st3.dis();

    mystring st4 = "this is a dog";
    st4.dis();
    
    return 0;
}

